package com.yunhaikeji.core.session;

import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * ServletSessionUtils
 *
 * @author : zhuo
 * @date : 2018/10/17 16:04
 * @description :
 */
@Component
public class ServletSessionUtils implements SessionUtils {

    private HttpSession getSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getSession();
    }

    @Override
    public void setAttribute(String key, Object value) {
        HttpSession session = getSession();
        if(session != null){
            session.setAttribute(key, value);
        }
    }

    @Override
    public <T> T getAttribute(String key) {
        HttpSession session = getSession();
        if(session != null){
            return (T)session.getAttribute(key);
        }
        return null;
    }

    @Override
    public void removeAttribute(String key) {
        HttpSession session = getSession();
        if(session != null){
            session.removeAttribute(key);
        }
    }
}
